Step 9: CI/CD

We must make two changes to our repository for Heroku to successfully deploy our server application.

First, we must add a Procfile to the hello-api folder with the following content

web: yarn start

A Procfile specifies the commands that are executed by the Heroku app on startup. Read more about it here.

Next, we must update the server.js as follows. Change this line

const port = 3000;

to the following:

const port = process.env.PORT || 3000;

The process.env.PORT || 3000 says assign the environment variable PORT as the port number, or 3000 if PORT is not defined. We need this change because Heroku will automatically assign a port to our application. It then stores the port number as an environment variable, PORT. We cannot tell Heroku which port to use! We must use what it assigns to our application.

Next, create a .github folder. Add a subfolder workflows to .github. Finally, add a deploy.yml file to this subfolder with the following content:

name: Deploy the server (backend) app

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: akhileshns/heroku-deploy@v3.12.12
        with:
          heroku_api_key: ${{secrets.HEROKU_AUTH_TOKEN}}
          heroku_app_name: ${{secrets.HEROKU_APP_NAME}}
          heroku_email: ${{secrets.HEROKU_AUTH_EMAIL}}
          appdir: "hello-api"

Note: You only need appdir: "hello-api" if your Express app is in a subfolder in your repository. Otherwise, simply remove this line.

Notice we need some information about the Heroku app along with our account email and API key. These are read from GitHub Secrets. We’ll set these in the next section.